package org.googlecode.viewt.core.po;

import org.googlecode.viewt.core.utils.TypeUtil;



public class POUtils {
	public static PODescriptor getPODescriptor(String poClassName)
			throws ClassNotFoundException, InstantiationException,
			IllegalAccessException {
		String descName = poClassName + "Descriptor";
		Class descClass = TypeUtil.loadClass(descName);

		if (descClass != null) {
			return ((PODescriptor) descClass.newInstance());
		}
		return null;
	}

	public static PODescriptor getPODescriptor(Class poClass)
			throws ClassNotFoundException, InstantiationException,
			IllegalAccessException {
		return getPODescriptor(poClass.getName());
	}

	public static String getPOClassName(String rootTag, String nsUrl) {
		String prefix = "http://www.";

		if (!(nsUrl.startsWith(prefix))) {
			return null;
		}
		String[] nsPacks = nsUrl.substring(prefix.length()).split("[/]");
		String[] hostSeg = nsPacks[0].split("[.]");
		String poClassName = "";
		for (int i = hostSeg.length; i > 0; --i) {
			if (i != hostSeg.length)
				poClassName = poClassName + ".";
			poClassName = poClassName + hostSeg[(i - 1)];
		}

		for (int i = 1; i < nsPacks.length; ++i) {
			poClassName = poClassName + "." + nsPacks[i];
		}
		return poClassName + "." + rootTag;
	}

	public static String getPOModule(String className) {
		if ((className == null) || ("".equals(className))) {
			return null;
		}
		int index = className.lastIndexOf(".po.");
		if (index < 0)
			return null;
		String moduleClassName = className.substring(0, index);
		index = moduleClassName.lastIndexOf(46);
		if (index < 0) {
			return null;
		}
		return moduleClassName.substring(index + 1);
	}

	public static String getPOProject(String className) {
		if ((className == null) || ("".equals(className))) {
			return null;
		}
		int index = className.lastIndexOf(".po.");
		if (index < 0)
			return null;
		String moduleClassName = className.substring(0, index);
		index = moduleClassName.lastIndexOf(46);
		if (index < 0)
			return null;
		String projectClassName = moduleClassName.substring(0, index);
		index = projectClassName.lastIndexOf(46);
		if (index < 0) {
			return null;
		}
		return projectClassName.substring(index + 1);
	}

	public static String shortClassName(String className) {
		return className.substring(className.lastIndexOf(46) + 1);
	}

	public static String getPackageName(String className) {
		int index = className.lastIndexOf(46);
		if (index < 0) {
			return null;
		}
		return className.substring(0, index);
	}
}